﻿// Copyright 2008 ESRI
// 
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
// 
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
// 
// See use restrictions at <your ArcGIS install location>/developerkit/userestrictions.txt.
// 

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BTGISWASECO.DataLayer;
using ESRI.ArcGIS.ADF.Web.Geometry;
using ESRI.ArcGIS.ADF.Web.UI.WebControls;
using System.Collections.Specialized;

public class IdentifyToolPolyline : ESRI.ArcGIS.ADF.Web.UI.WebControls.Tools.IMapServerToolAction
{
    #region Member variables that can be customized

    /* Column names to exclude from Identify.
         * "Display Column", "GRAPHICS_ID", "IS_SELECTED" and columns of type ADF geometry are already set by the framework to not be visible.
         * GraphicsLayer.GetContentsTemplate honors this visibility setting.*/
    private string[] excludedColumnNames = { "OID", "ObjectID", 
            "#ID#" , 
            "#SHAPE#"};//likely of type IMS geometry

    private string _identifyIconUrl = "images/identify-map-icon.png";
    private string _waitIconUrl = "images/callbackActivityIndicator2.gif";
    private int _identifyTolerance = 4; // tolerance used in identify request... may need to be adjusted to a specific resource type
    private ESRI.ArcGIS.ADF.Web.IdentifyOption _idOption = ESRI.ArcGIS.ADF.Web.IdentifyOption.VisibleLayers;
    private string _mapBuddyId = "Map1";
    private string _taskResultsId = "TaskResults1";
    private int _numberDecimals = 5; //number of decimals in coordinate string
    private bool _isRTL = false;
    #endregion

    #region Member variables
    private string _id;
    private Map _map;
    #endregion
    #region IMapServerToolAction Members

    void ESRI.ArcGIS.ADF.Web.UI.WebControls.Tools.IMapServerToolAction.ServerAction(
        ESRI.ArcGIS.ADF.Web.UI.WebControls.ToolEventArgs toolEventArgs)
    {
        // Get reference to the map control
        ESRI.ArcGIS.ADF.Web.UI.WebControls.Map adfMap =
            (ESRI.ArcGIS.ADF.Web.UI.WebControls.Map)toolEventArgs.Control;


        Map map = adfMap;
try
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.WebControl s = (ESRI.ArcGIS.ADF.Web.UI.WebControls.WebControl)toolEventArgs.Control;
        ESRI.ArcGIS.ADF.Web.UI.WebControls.MapPointEventArgs mapPointEventArgs =
            (ESRI.ArcGIS.ADF.Web.UI.WebControls.MapPointEventArgs)toolEventArgs;
        ESRI.ArcGIS.ADF.Web.Geometry.Point adfPoint = mapPointEventArgs.MapPoint;
        CallbackResult cResponse = PointIdentify(map, adfPoint);
        map.Dispose();
        }
        catch (System.Exception exception)
        {
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult errorAlertCallbackResult =
                Utility.CreateErrorCallbackResult(exception);
            adfMap.CallbackResults.Add(errorAlertCallbackResult);
        }

    }
    #endregion


    private CallbackResult PointIdentify(Map map, ESRI.ArcGIS.ADF.Web.Geometry.Point mapPoint)
    {
        #region Collections to store results
        System.Collections.ArrayList identifyResults = new System.Collections.ArrayList(); //to send to client
        System.Collections.Generic.List<DataTable> tbList = new System.Collections.Generic.List<DataTable>(); //to store on server for "Add to Results" behavior
        #endregion

        #region Variable declarations
        System.Collections.Generic.Dictionary<string, string> identifyResultItem; //a dictionary to hold info on a result item
        ESRI.ArcGIS.ADF.Web.DataSources.IGISResource resource;
        ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality query;
        System.Data.DataTable[] identifyDataTables = null;
        string tableName;
        string dsName = "";
        System.Data.DataTable identifyTable = null;
        System.Data.DataTable EditTable = null;
        System.Data.DataRowCollection rowCollection = null;
        #endregion

        foreach (ESRI.ArcGIS.ADF.Web.DataSources.IMapFunctionality mapFunc in map.GetFunctionalities())
        {
            if (mapFunc.DisplaySettings.Visible)
            {
                resource = mapFunc.Resource;
                query = resource.CreateFunctionality(typeof(ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality), "identify_") as ESRI.ArcGIS.ADF.Web.DataSources.IQueryFunctionality;

                if ((query != null) && (query.Supports("identify")))
                {
                    #region Perform the identify query
                    // create a list of layer ids for the identify request
                    string[] layerNames = null;
                    string[] layerIDs = null;
                    query.GetQueryableLayers(null, out layerIDs, out layerNames);
                    try
                    {
                        identifyDataTables = query.Identify(mapFunc.Name, mapPoint, _identifyTolerance, _idOption, layerIDs);
                    }
                    catch
                    {
                        identifyDataTables = null;
                    }
                    #endregion

                    #region Process result tables
                    if (identifyDataTables != null && identifyDataTables.Length > 0)
                    {
                        for (int index = 0; index < identifyDataTables.Length; index++)
                        {

                            if (EditTable==null)
                            switch (identifyDataTables[index].TableName)
                            {
                                //  Ống nhánh - Cấp 3 Van
                                case "Ống phân phối - cấp 2":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Ống truyền dẫn - Cấp 1":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Ống nhánh - Cấp 3":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Van":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Van khách hàng":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Điểm đấu nối":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Đồng hồ tổng":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Máy bơm":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Trụ cứu hỏa, họng lấy nước":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Trạm bơm":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Hầm van":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Bể chứa":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "DatLogger":
                                    EditTable = identifyDataTables[index];
                                    break;
                                case "Đồng hồ Khách hàng":
                                    EditTable = identifyDataTables[index];
                                    break;
                            }//

                            identifyTable = identifyDataTables[index];
                            tableName = identifyTable.ExtendedProperties[ESRI.ArcGIS.ADF.Web.Constants.ADFLayerName] as string;
                            if (string.IsNullOrEmpty(tableName))
                                tableName = identifyDataTables[index].TableName;

                            #region Get template for title and contents for this layer from Map Resource Manager

                            #region Get layer format and apply it
                            string layerID = identifyTable.ExtendedProperties[ESRI.ArcGIS.ADF.Web.Constants.ADFLayerID] as string;
                            LayerFormat layerFormat = null;
                            DataTable formattedTable = identifyTable;
                            if (!string.IsNullOrEmpty(layerID))
                            {
                                layerFormat = LayerFormat.FromMapResourceManager(map.MapResourceManagerInstance, mapFunc.Resource.Name, layerID);
                                if (layerFormat != null)
                                {
                                    ESRI.ArcGIS.ADF.Web.Display.Graphics.GraphicsLayer layer = ESRI.ArcGIS.ADF.Web.Converter.ToGraphicsLayer(
                                        identifyTable, System.Drawing.Color.Empty, System.Drawing.Color.Aqua, System.Drawing.Color.Red, true);
                                    if (layer != null)
                                    {
                                        layerFormat.Apply(layer);
                                        formattedTable = layer;
                                    }
                                }
                            }
                            #endregion

                            #region Get template for title and contents
                            string contentsTemplate = ESRI.ArcGIS.ADF.Web.Display.Graphics.GraphicsLayer.GetContentsTemplate
                                (formattedTable, false, System.Drawing.Color.Empty, true, excludedColumnNames);
                            string titleTemplate = ESRI.ArcGIS.ADF.Web.Display.Graphics.GraphicsLayer.GetTitleTemplate(
                                formattedTable, false);
                            #region Apply templates back to layer format to account for excluded column names
                            if (layerFormat != null && excludedColumnNames.Length > 0)
                            {
                                layerFormat = layerFormat.Clone() as LayerFormat;//clone layer format so that we do not change the layer format stored in the map resource manager
                                //exclude column names and get template with field names instead of indices
                                layerFormat.Contents = ESRI.ArcGIS.ADF.Web.Display.Graphics.GraphicsLayer.GetContentsTemplate(
                                    formattedTable, true, System.Drawing.Color.LightGray, true, excludedColumnNames);
                            }

                            
                            //HttpContext.Current.Response.Redirect("PresentationLayer/OngPhanPhoi.aspx");
                            #endregion
                            #endregion
                            #endregion
                        }
                    }
                    else
                    {
                        return null;
                    }
                    #endregion
                }
            }
        }
        System.Web.HttpContext.Current.Session.Add("WebAppIdentifyDataTables", tbList.ToArray());

        #region Create callback result to send to client
        //Note: arrays and dictionaries are handled natively by the JSON serialization framework
        //
        string jsSetDivVisibility;
        if (EditTable!=null)
        switch (EditTable.TableName)
        {
            // The following switch section causes an error.
            case "Ống phân phối - cấp 2":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/OngPhanPhoi.aspx','_parent')";
                break;
            case "Ống truyền dẫn - Cấp 1":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/OngTruyenDan.aspx','_parent')";
                break;
            case "Ống nhánh - Cấp 3":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/OngNhanh.aspx','_parent')";
                break;
            case "Van":
                 HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/Van.aspx','_parent')";
                break;
            case "Van khách hàng":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/VanKhachHang.aspx','_parent')";
                break;
            case "Điểm đấu nối":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/DiemDauNoi.aspx','_parent')";
                break;
            case "Đồng hồ tổng":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/DongHoTong.aspx','_parent')";
                break;
            case "Máy bơm":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/MayBom.aspx','_parent')";
                break;
            case "Trụ cứu hỏa, họng lấy nước":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/TruHong.aspx','_parent')";
                break;
            case "Trạm bơm":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/TramBom.aspx','_parent')";
                break;
            case "Hầm van":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/HamVan.aspx','_parent')";
                break;
            case "Bể chứa":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/BeChua.aspx','_parent')";
                break;
            case "DatLogger":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/DataLogger.aspx','_parent')";
                break;
            case "Đồng hồ Khách hàng":
                HttpContext.Current.Session["DataTable"] = EditTable;
                jsSetDivVisibility = "window.open('PresentationLayer/DongHoCon.aspx','_parent')";
                break;
            default:
                jsSetDivVisibility = "alert('Dữ liệu không thuôc danh mục chỉnh sửa.')";//TramBom.aspx
                break;
        }
        else jsSetDivVisibility = "alert('Dữ liệu không thuôc danh mục chỉnh sửa.')";
        //string jsSetDivVisibility = "window.open('PresentationLayer/OngPhanPhoi.aspx','_parent')";// "writer.WriteLine('<script type=\'text/javascript\' src=\'JavaScript/MapIdentify.js\'></script>');";
        //    //           "document.getElementById('identifyResultsDiv').style.visibility = 'visible';";
        ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult setVisibilityCallbackResult =
            ESRI.ArcGIS.ADF.Web.UI.WebControls.CallbackResult.CreateJavaScript(jsSetDivVisibility);
        map.CallbackResults.Add(setVisibilityCallbackResult);
        map.Dispose();
        return setVisibilityCallbackResult;
        //
       // return new CallbackResult("this","Thong", "mappoint", identifyResults);
        #endregion
    }
}


